package ops.view;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JPanel;

import ops.controller.ControllerManager;
import ops.controller.GradesController;
import ops.i18n.Resources;
import ops.util.ViewHelper;
import ops.view.tables.Column;
import ops.view.tables.TableMaker;

public class AddGradesPanel extends JPanel implements Refreshable {

	private GradesController gradesController = ControllerManager.getInstance().getGradesController();
	
	private JPanel buttonsPanel, formPanel;

	private JButton saveButton;
	private JButton removeButton;

	private TableMaker tableMaker;
	
	public AddGradesPanel() {
		super(new BorderLayout());
		
		init();
	}
	
	public void clearTable() {
		tableMaker.clearTable();
	}
	
	public void addRowToTable(Object... data) {
		tableMaker.addRow(data);
	}

	private void init() {
		
		formPanel = new JPanel(new BorderLayout());

		initButtons();
		initTable();

		add(formPanel, BorderLayout.SOUTH);
	}
	
	private void initTable() {
		Resources resources = Resources.getInstance();

		tableMaker = new TableMaker();
		tableMaker.addColumn(new Column(resources.getString("course.code"), Integer.class, 15));
		tableMaker.addColumn(new Column(resources.getString("name"), String.class, 70));
		tableMaker.addColumn(new Column(resources.getString("grade"), Integer.class, 15, true));

		add(ViewHelper.makeScrollPane(tableMaker.getTable()), BorderLayout.CENTER);
	}

	private void initButtons() {
		buttonsPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 5));

		ButtonListener listener = new ButtonListener();

		removeButton = ViewHelper.makeRemoveButton();
		removeButton.addActionListener(listener);
		saveButton = ViewHelper.makeSaveButton();
		saveButton.addActionListener(listener);

		buttonsPanel.add(saveButton);
		buttonsPanel.add(removeButton);

		formPanel.add(buttonsPanel, BorderLayout.CENTER);
	}


	private class ButtonListener implements ActionListener {
		Long code;
		public void actionPerformed(ActionEvent e) {
			if (!(e.getSource() instanceof JButton)) {
				return;
			}
			
			JButton button = (JButton) e.getSource();
			saveButton.setEnabled(true);
			if (!button.isEnabled()) {
				return;
			}
			
			for (int i = 0; (tableMaker.getValueAt(i, 0) != null); i++) {
				code = (Long) tableMaker.getValueAt(i, 0);
				String name = (String) tableMaker.getValueAt(i, 1);
				int grade = (Integer) tableMaker.getValueAt(i, 2); 
			}

			if (button == saveButton) {
				
				saveButton.setEnabled(false);
				gradesController.endAddProcess();
			} else if (button == removeButton) {
				gradesController.removeGrade(code);
			} 
		}
	}
	

	public void refresh() {
		gradesController.updateTable();
	}
}
